package com.example.securitydemo.controller;

import com.example.securitydemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;

/**
 * @author zhangyx
 * @desc
 * @date 2020/8/12 16:52
 **/
@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    /*@GetMapping("/123")
    public String loginPage(){
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public String login(UserDto userDto){
        userDto = userService.login(userDto.getUsername(),userDto.getPassword());
        return userDto.getUsername()+":登录成功";
    }*/

    @PostMapping(value = "/login-success",produces = "text/plain;charset=UTF-8")
    public String loginSuccess(){
        return getUserName()+"登录成功";
    }

    @GetMapping(value = "/r/p1",produces = "application/json;charset=UTF-8")
    public String getP1(){
        return getUserName()+"资源p1";
    }

    @GetMapping(value = "/r/p2",produces = "application/json;charset=UTF-8")
    public String getP2(){
        return getUserName()+"资源p2";
    }

    private String getUserName(){
        String username = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if(principal==null){
            username = "匿名";
        }else if(principal instanceof UserDetails){
            UserDetails userDetails = (UserDetails) principal;
            username = userDetails.getUsername();
        }else {
            username = principal.toString();
        }
        return username;
    }
}
